package com.sales.controller;

import com.sales.dao.StoreDao;
import com.sales.entity.Store;
import com.sales.excption.SalesException;
import com.sales.service.CommissionDetailsService;
import com.sales.signUpReq.CommissionSignUpReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * Created by lihu on 2017/10/21.
 */

@Slf4j
@RestController
@RequestMapping(value = "/api/v1/sales", produces = "application/json;charset=utf-8")
public class CommissionDetailsController {

    @Autowired
    StoreDao storeDao;

    @Autowired
    CommissionDetailsService commissionDetailsService;

    /**
     * 提成记录 同步
     *
     * @param signUpReq
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/commission")
    public ResponseEntity commission(@Valid @RequestBody CommissionSignUpReq signUpReq,
                                     BindingResult bindingResult) {
        try {
            //参数校验
            if (bindingResult.hasErrors()) {
                log.info("【提成记录同步失败】参数不正确, signUpReq={}", signUpReq);
                return new ResponseEntity(bindingResult.getFieldError().getDefaultMessage(),
                        HttpStatus.BAD_REQUEST);
            }
            Store store = storeDao.findOne(signUpReq.getStoreId());
            if (store == null) {
                log.info("【提成记录同步失败】店铺信息不存在, signUpReq={}", signUpReq);
                return new ResponseEntity("店铺信息不存在！",
                        HttpStatus.BAD_REQUEST);
            }

            commissionDetailsService.commissionSync(store);
            return new ResponseEntity(HttpStatus.OK);
        } catch (SalesException ex) {
            log.error("commission is error=>signUpReq:{}", signUpReq, ex);
            return new ResponseEntity(ex.getMessage(), HttpStatus.BAD_REQUEST);
        } catch (Exception ex) {
            log.error("commission is error=>signUpReq:{}", signUpReq, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }
}
